package org.threebitsoftware.tbb.Contact_GUI;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;

import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.threebitsoftware.dao.generated.Contactphoto;
import org.threebitsoftware.tbb.dao.Contact;
import org.threebitsoftware.tbb.engine.EngineUtil;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;

public class PhotoImport extends Dialog {
	private static Logger logger = Logger.getLogger(PhotoImport.class);
	private Text pathText_;
	private Shell shlContactPhotoImport;
	private Object result_;
	private Contact currentContact;
	
	/**
	 * Create the shell.
	 * 
	 * @param display
	 */
	public PhotoImport(Shell parent, int style, Contact selectedContact) {
		super(parent, style);
		setText("SWT Dialog");
		currentContact = selectedContact;
	}
	
	public PhotoImport (Shell parent, int style){
		super(parent, style);
	}

	public Object open() {
		createContents();
		shlContactPhotoImport.open();
		shlContactPhotoImport.layout();
		
		Display display = getParent().getDisplay();

		while (!shlContactPhotoImport.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result_;
	}

	/**
	 * Create the shell.
	 * 
	 * @param display
	 * Create contents of the shell.
	 */
	protected void createContents() {
		shlContactPhotoImport = new Shell(getParent(), SWT.DIALOG_TRIM
				| SWT.APPLICATION_MODAL);
		shlContactPhotoImport.setBackground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		shlContactPhotoImport.setSize(473, 87);
		shlContactPhotoImport.setText("Import Photo for Current Contact");
		
		/**
		 *  handle the path text box
		 */
		{
			pathText_ = new Text(shlContactPhotoImport, SWT.BORDER);
			pathText_.setBounds(64, 7, 321, 19);
		}
		
		/**
		 * handle the export button
		 */
		{
			Button btnImport = new Button(shlContactPhotoImport, SWT.NONE);
			btnImport.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					// PhotoService read the photo file and return it back here
					// currentContact.setPhoto(/*byte[] photoSerivice.readPhoto()*/);
					
					
					if (!pathText_.getText().isEmpty() && currentContact!=null){//upload the photo from the file path
//						photoData = new ImageData(pathText_.getText());
//						contactPhotoByteArray = photoData.data;
						Contactphoto contactPhoto = new Contactphoto();
						
						contactPhoto.setIdContact(currentContact.getIdContact());
						contactPhoto.setSDescription("Photo of Contact: " + currentContact.getFirstName());
						
						if (currentContact.getPhoto()!=null){
							//Update the old Contact photo with the new one.
							boolean photoUpdateStatus = EngineUtil.setPhotoImport(contactPhoto, "org.threebitsoftware.tbb.module.photo.ContactPhoto", pathText_.getText(),"update");
							logger.debug("Updated the photo for Contact: " + currentContact.toString());
							System.out.println("Updated photo for Contact: " + currentContact.toString());
							
							InsertUpdateStatus(photoUpdateStatus, "update");
							
						} else if (currentContact.getPhoto()==null){
							//create a new Photo for the Contact
							boolean photoInsertStatus = EngineUtil.setPhotoImport(contactPhoto, "org.threebitsoftware.tbb.module.photo.ContactPhoto", pathText_.getText(),"insert");
							logger.debug("Added the photo for Contact: " + currentContact.toString());
							System.out.println("Added photo for Contact: " + currentContact.toString());

							InsertUpdateStatus(photoInsertStatus, "insert");
						}
						

						
					} else if (pathText_.getText().isEmpty()){//no photo path provided
						JOptionPane.showMessageDialog(null,"Please provide location of the photo.",
								null, 
								JOptionPane.NO_OPTION);
					} else if (currentContact==null){
						JOptionPane.showMessageDialog(null,"Please sellect one contact.",
								null, 
								JOptionPane.NO_OPTION);
					}

//					} else if (photoData==null){
//						System.out.println("Error Adding photo for Contact: " + currentContact.toString());
//						logger.error("Error Adding photo for Contact: " + currentContact.toString());
//					}
					
					
				}
			});
			btnImport.setBounds(214, 32, 68, 23);
			btnImport.setText("&Import");
		}
		
		/**
		 * handle the path label
		 */
		{	Label lblPath = new Label(shlContactPhotoImport, SWT.NONE);
			lblPath.setBounds(10, 10, 48, 19);
			lblPath.setText("Path");
		}
		{
			Button btnCancel = new Button(shlContactPhotoImport, SWT.NONE);
			btnCancel.addMouseListener(new MouseAdapter() {
				/**
				 * on mouse click of cancel button close this gui
				 */
				@Override
				public void mouseDown(MouseEvent e) {
					shlContactPhotoImport.close();
				}
			});
			btnCancel.setBounds(140, 32, 68, 23);
			btnCancel.setText("&Cancel");
		}
		
		/**
		 * handle the browse button
		 */
		{
			Button btnBrowse = new Button(shlContactPhotoImport, SWT.NONE);
			btnBrowse.addMouseListener(new MouseAdapter() {
				
				/**
				 * Open file browser when the browse button is pressed
				 */
				@Override
				public void mouseDown(MouseEvent e) {
					FileDialog openDialog = new FileDialog(new Shell(), SWT.SAVE);
					openDialog.setFilterExtensions(new String[] {"*.jpg","*.gif"});
					openDialog.open();
					pathText_.setText(openDialog.getFilterPath() != "" ? 
							openDialog.getFilterPath()+ "\\" + 
							openDialog.getFileName() : "");
				}
			});

			btnBrowse.setBounds(389, 5, 68, 23);
			btnBrowse.setText("&Browse");
		}
	}
	
	/**
	 * Display meassage box based on if the Photo Insert/update was successful/unsuccessful.
	 * @param updateStatus
	 * @param queryType
	 */
	private void InsertUpdateStatus (boolean updateStatus, String queryType){
		
		String successMessage = "Photo " + queryType + " successful";
		String errorMessage = "Could not " + queryType + " photo";
		
		if (updateStatus){//update successfully
			JOptionPane.showMessageDialog(null,successMessage,
					null, 
					JOptionPane.NO_OPTION);
			shlContactPhotoImport.close();
			
		} else if (!updateStatus){//could not update 
			JOptionPane.showMessageDialog(null,errorMessage,
					null, 
					JOptionPane.NO_OPTION);
			
		}
	}
}
